package cn.kgc.vue.shiro;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author: 课工场
 * @Version: v1.0  2023/8/10
 * @Description: 自定义Filter  替换原来的authc的过滤器 实现请求的拦截处理
 * JWTFilter中  对请求中的token进行判定
 * 1.访问受限资源 判定是否携带token   否  跳转登录页  是 判定token的真伪
 */
public class JWTFilter  extends BasicHttpAuthenticationFilter {

    // 执行登录认证
    @Override
    protected boolean executeLogin(ServletRequest request, ServletResponse response) throws Exception {
        //System.out.println("===========executeLogin============");
        // 获取请求中的token
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        String token = httpRequest.getHeader("token");
        if (StringUtils.isEmpty(token)){
            throw  new AuthenticationException("请认证后访问!!!");
        }
        // 验证token  JWTToken
        Subject subject = getSubject(request, response);
        JWTToken jwtToken = new JWTToken(token);
        subject.login(jwtToken);

        return super.executeLogin(request, response);
    }

    // 判定请求是否被允许
    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        //System.out.println("===========isAccessAllowed============");
        try {
            executeLogin(request,response);
            return  true;
        } catch (Exception e) {
            e.printStackTrace();
            throw  new AuthenticationException("请认证后访问!!!");
        }
    }

    // 请求的前置处理  跨域处理
    @Override
    protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
        //System.out.println("===========preHandle============");
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        httpServletResponse.setHeader("Access-control-Allow-Origin", httpServletRequest.getHeader("Origin"));
        httpServletResponse.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS,PUT,DELETE");
        httpServletResponse.setHeader("Access-Control-Allow-Headers", httpServletRequest.getHeader("Access-Control-Request-Headers"));
        // 跨域时会首先发送一个option请求，这里我们给option请求直接返回正常状态
        if (httpServletRequest.getMethod().equals(RequestMethod.OPTIONS.name())) {
            httpServletResponse.setStatus(HttpStatus.OK.value());
            return false;
        }
        return super.preHandle(request, response);
    }
}
